package com.buaa.utility.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.buaa.utility.Constants;
import com.buaa.utility.action.UserAction;
import com.buaa.utility.services.SystemConfiguration;


public class ActionController extends HttpServlet {
	private Map<String,Action> uriMap;
	private String errorPage;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SystemConfiguration.init(this);
		errorPage = this.getInitParameter("errorPage");
		
		uriMap = new Hashtable<String,Action>();
		uriMap.put("/userAction.act",new UserAction());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.print("=======================");
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String path = request.getServletPath();//getRequestURI();
		String method = request.getParameter("method");
		if(path==null || "".equals(path.trim())){
			response.sendError(404);
			return;
		}
		
		Action action = uriMap.get(path);
		System.out.println("path:"+path);
		System.out.println("action:"+action);
		System.out.println("method:"+method);
		if(action==null){
			response.sendError(404);
			return;
		}
		
		if(method==null || "".equals(method.trim())){
			try {
				action.execute(request,response);
			} catch (Exception e) {
				request.setAttribute(Constants.REQUEST_KEY_ACTION_EXCEPTION,e);
				Action.forward(errorPage,request,response);
			}
		}else{
			Method m = null;
			try {
				m = action.getClass().getMethod(method,new Class[]{HttpServletRequest.class,HttpServletResponse.class});
			} catch (Exception e) {
				response.sendError(404);
				return;
			}
			
			if(m!=null){
				try {
					m.invoke(action,new Object[]{request,response});
				} catch (Exception e) {
					e.printStackTrace();
					if(e instanceof InvocationTargetException){
						InvocationTargetException ee = (InvocationTargetException) e;
						request.setAttribute(Constants.REQUEST_KEY_ACTION_EXCEPTION,ee.getTargetException());
					}else{
						request.setAttribute(Constants.REQUEST_KEY_ACTION_EXCEPTION,e);
					}
					
					Action.forward(errorPage,request,response);
				}
			}
		}
	}
}
